<!DOCTYPE html>
<html lang="zh-CN">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script>
    <style>
        :root {
            --primary-color: #1890ff;
            --success-color: #52c41a;
            --error-color: #ff4d4f;
            --text-dark: #1f2d3d;
            --text-light: #5e6c84;
            --border-color: #e4e7ed;
            --shadow-default: 0 4px 12px rgba(0, 0, 0, 0.08);
            --glow-color: #40a9ff;
        }

        body {
            margin: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
            line-height: 1.5;
            background: #f5f7fa;
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 240px;
            background: white;
            box-shadow: var(--shadow-default);
            padding: 20px 0;
        }

        .nav-title {
            color: var(--text-dark);
            font-size: 16px;
            padding: 12px 24px;
            font-weight: 600;
        }

        .nav-item {
            display: flex;
            align-items: center;
            padding: 12px 24px;
            color: var(--text-dark);
            text-decoration: none;
            transition: all 0.2s;
            cursor: pointer;
        }

        .nav-item.active {
            background: #f5f5f5;
            color: var(--primary-color);
            border-right: 3px solid var(--primary-color);
        }

        .nav-item:hover {
            background: #f5f5f5;
        }

        .main-content {
            flex: 1;
            padding: 32px;
            max-width: 1200px;
        }

        .content-section {
            display: none;
        }

        .content-section.active {
            display: block;
        }

        .ant-card {
            background: white;
            padding: 32px;
            border-radius: 12px;
            box-shadow: var(--shadow-default);
            margin-bottom: 24px;
        }

        .ant-title {
            color: var(--text-dark);
            font-size: 20px;
            margin: 0 0 24px;
            font-weight: 600;
            position: relative;
            padding-left: 12px;
        }

        .ant-title::before {
            content: '';
            position: absolute;
            left: 0;
            top: 4px;
            bottom: 4px;
            width: 3px;
            background: var(--primary-color);
            border-radius: 2px;
        }

        .ant-btn {
            padding: 12px 24px;
            background: var(--primary-color);
            border: none;
            color: white;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }

        .ant-btn:hover {
            background: #40a9ff;
            transform: translateY(-1px);
            box-shadow: var(--shadow-default);
        }

        .ant-alert {
            padding: 12px;
            border-radius: 6px;
            margin-top: 16px;
            display: none;
        }

        .ant-input[type="file"] {
            padding: 10px;
            border: 2px dashed var(--border-color);
            border-radius: 6px;
            width: 100%;
            cursor: pointer;
            transition: border-color 0.3s;
        }

        .ant-input[type="file"]:hover {
            border-color: var(--primary-color);
        }

        .ant-alert-success {
            background: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }

        .ant-alert-error {
            background: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }

        .flowchart-container {
            width: 100%;
            background: white;
            padding: 20px;
            border-radius: 12px;
            box-shadow: var(--shadow-default);
            margin-top: 20px;
            text-align: center;
            position: relative;
        }

        .flowchart-container svg {
            overflow: visible;
        }

        .flowchart-step {
            fill: #e8ecef;
            stroke: #d3d7dc;
            stroke-width: 2;
            rx: 15;
            ry: 15;
            filter: drop-shadow(0 4px 6px rgba(0, 0, 0, 0.1));
            transition: fill 0.3s ease, stroke 0.3s ease, transform 0.3s ease;
        }

        .flowchart-step.active {
            fill: url(#gradient);
            stroke: var(--primary-color);
            transform: scale(1.05);
            animation: glow 1.5s infinite alternate;
        }

        .flowchart-text {
            font-size: 14px;
            fill: var(--text-dark);
            font-weight: 500;
            transition: fill 0.3s ease;
        }

        .flowchart-text.active {
            fill: white;
        }

        @keyframes glow {
            from {
                box-shadow: 0 0 5px var(--glow-color);
            }
            to {
                box-shadow: 0 0 15px var(--glow-color);
            }
        }

        .tooltip {
            position: absolute;
            background: #333;
            color: white;
            padding: 8px 12px;
            border-radius: 8px;
            font-size: 12px;
            pointer-events: none;
            opacity: 0;
            transform: translateY(10px);
            transition: opacity 0.3s ease, transform 0.3s ease;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            z-index: 10;
        }

        .tooltip.visible {
            opacity: 1;
            transform: translateY(0);
        }

        .loading-spinner {
            display: none;
            margin: 20px auto;
            text-align: center;
        }

        .loading-spinner.active {
            display: block;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid transparent;
            border-right: 4px solid var(--primary-color);
            border-left: 4px solid var(--primary-color);
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .loading-text {
            font-size: 14px;
            color: var(--text-dark);
        }

        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
                padding: 10px 0;
            }

            .nav-item {
                padding: 10px 15px;
            }

            .main-content {
                padding: 20px;
            }

            .flowchart-container {
                margin-top: 10px;
            }

            .tooltip {
                font-size: 10px;
                padding: 6px 10px;
            }
        }

        .platform-name {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* 渐变填充 */
        defs {
            position: absolute;
        }
        defs linearGradient#gradient {
            stop:nth-child(1) { stop-color: #1890ff; stop-opacity: 1; }
            stop:nth-child(2) { stop-color: #40a9ff; stop-opacity: 1; }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧导航 -->
        <div class="sidebar">
            <div class="nav-title">功能导航</div>
            <a href="/admin/user-management/" class="nav-item">📝 管理员入口</a>
            <a href="#survey_create" class="nav-item">📝 创建问卷</a>
            <a href="#data-pipeline" class="nav-item active">📊 数据分析流程</a>
            <a href="survey_list" class="nav-item">📋 问卷列表</a>
            <div class="nav-title" style="margin-top: 40px;">账号</div>
            <div class="nav-item">👤 {{ user.username }}</div>
            <a href="{% url 'logout' %}" class="nav-item">🚪 退出登录</a>
        </div>

        <!-- 右侧内容 -->
        <div class="main-content">
            <!-- 创建问卷 -->
            <div id="survey_create" class="content-section">
                <div class="ant-card">
                    <h2 class="ant-title">创建新问卷</h2>
                    <a href="{% url 'survey_create' %}" class="ant-btn"
                       style="width: 100%; margin-bottom: 20px; text-decoration: none;">
                        🚀 立即创建
                    </a>
                </div>
            </div>

            <!-- 问卷列表 -->
            <div id="survey_list" class="content-section">
                <div class="ant-card">
                    {% include "survey_list.html" %}
                </div>
            </div>

            <!-- 数据分析流程 -->
            <div id="data-pipeline" class="content-section active">
                <div class="ant-card">
                    <h2 class="ant-title">数据分析流程</h2>
                    <form id="pipeline-form" enctype="multipart/form-data">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="file-input">1. 上传数据</label>
                            <input type="file" name="file" class="ant-input" id="file-input" required accept=".csv">
                            <small style="color: var(--text-light); font-size: 12px;">仅支持 .csv 格式文件</small>
                        </div>
                        <div class="form-group">
                            <label for="filename">2. 当前处理文件</label>
                            <input type="text" name="filename" id="filename" class="ant-input" readonly>
                        </div>
                        <button type="submit" class="ant-btn" id="start-pipeline">开始分析</button>
                    </form>
                    <div id="pipeline-status" class="ant-alert"></div>
                    <div id="results" style="margin-top: 20px;"></div>
                </div>

                <!-- 横向流程图 -->
                <div class="flowchart-container">
                    <h3>分析流程</h3>
                    <svg width="100%" height="150" id="flowchart">
                        <defs>
                            <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
                                <stop offset="0%" style="stop-color:#1890ff;stop-opacity:1" />
                                <stop offset="100%" style="stop-color:#40a9ff;stop-opacity:1" />
                            </linearGradient>
                        </defs>
                        <g>
                            <rect x="100" y="50" width="150" height="60" rx="15" ry="15" class="flowchart-step" id="step-upload"/>
                            <text x="175" y="80" text-anchor="middle" class="flowchart-text" id="text-upload">数据上传</text>
                            <path d="M250 80 H300" fill="none" stroke="#d3d7dc" stroke-width="2"/>
                            <path d="M290 70 L300 80 L290 90" fill="none" stroke="#d3d7dc" stroke-width="2"/>
                            <rect x="300" y="50" width="150" height="60" rx="15" ry="15" class="flowchart-step" id="step-preprocess"/>
                            <text x="375" y="80" text-anchor="middle" class="flowchart-text" id="text-preprocess">数据预处理</text>
                            <path d="M450 80 H500" fill="none" stroke="#d3d7dc" stroke-width="2"/>
                            <path d="M490 70 L500 80 L490 90" fill="none" stroke="#d3d7dc" stroke-width="2"/>
                            <rect x="500" y="50" width="150" height="60" rx="15" ry="15" class="flowchart-step" id="step-analysis"/>
                            <text x="575" y="80" text-anchor="middle" class="flowchart-text" id="text-analysis">数据分析</text>
                            <path d="M650 80 H700" fill="none" stroke="#d3d7dc" stroke-width="2"/>
                            <path d="M690 70 L700 80 L690 90" fill="none" stroke="#d3d7dc" stroke-width="2"/>
                            <rect x="700" y="50" width="150" height="60" rx="15" ry="15" class="flowchart-step" id="step-results"/>
                            <text x="775" y="80" text-anchor="middle" class="flowchart-text" id="text-results">聚类结果</text>
                        </g>
                    </svg>
                    <div class="tooltip" id="flowchart-tooltip"></div>
                    <div class="loading-spinner" id="loading-spinner">
                        <div class="spinner"></div>
                        <div class="loading-text" id="loading-text"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        $(document).ready(function () {
            // 更新流程图状态并显示提示
            function updateFlowchart(step, message) {
                $('.flowchart-step').removeClass('active');
                $('.flowchart-text').removeClass('active');
                $(`#step-${step}`).addClass('active');
                $(`#text-${step}`).addClass('active');

                // 显示工具提示
                const $tooltip = $('#flowchart-tooltip');
                const $step = $(`#step-${step}`);
                const stepOffset = $step[0].getBoundingClientRect();
                const containerOffset = $('.flowchart-container')[0].getBoundingClientRect();
                $tooltip.text(message).css({
                    left: stepOffset.left - containerOffset.left + (stepOffset.width / 2) - ($tooltip.outerWidth() / 2),
                    top: stepOffset.top - containerOffset.top - 40
                }).addClass('visible');

                setTimeout(() => $tooltip.removeClass('visible'), 2000);
            }

            // 状态显示函数
            function showStatus(message, success) {
                const $element = $('#pipeline-status');
                const icon = success ?
                    '<svg viewBox="0 0 24 24" width="18" height="18" fill="#52c41a"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>' :
                    '<svg viewBox="0 0 24 24" width="18" height="18" fill="#ff4d4f"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg>';

                $element.html(icon + ' ' + message)
                    .removeClass('ant-alert-success ant-alert-error')
                    .addClass(success ? 'ant-alert-success' : 'ant-alert-error')
                    .fadeIn(300)
                    .delay(3000)
                    .fadeOut(500);
            }

            // 显示加载动画
            function showLoading(message) {
                $('#loading-text').text(message);
                $('#loading-spinner').addClass('active');
            }

            // 隐藏加载动画
            function hideLoading() {
                $('#loading-spinner').removeClass('active');
            }

            // 初始化导航状态
            function initNavigation() {
                $('.content-section').removeClass('active');
                $('#data-pipeline').addClass('active');

                if (window.location.hash) {
                    const target = $(window.location.hash);
                    if (target.length) {
                        $('.nav-item').removeClass('active');
                        $(`.nav-item[href="${window.location.hash}"]`).addClass('active');
                        $('.content-section').removeClass('active');
                        target.addClass('active');
                    }
                }
            }

            // 导航点击事件
            $('.nav-item[href^="#"]').on('click', function (e) {
                e.preventDefault();
                const targetId = $(this).attr('href');
                $('.nav-item').removeClass('active');
                $(this).addClass('active');
                $('.content-section').removeClass('active');
                $(targetId).addClass('active');
                window.location.hash = targetId;
            });
            // 监听文件选择，实时显示文件名
                $('#file-input').on('change', function () {
                    const file = this.files[0];
                    if (file) {
                        $('#filename').val(file.name); // 显示原始文件名
                    } else {
                        $('#filename').val(''); // 清空输入框
                    }
                });
            // 数据分析流程处理
            $('#pipeline-form').on('submit', function (event) {
                event.preventDefault();
                const fileInput = $('#file-input')[0];
                const file = fileInput.files[0];

                if (file && !file.name.endsWith('.csv')) {
                    showStatus('不支持此格式文件，请重新上传 .csv 文件', false);
                    fileInput.value = '';
                    return;
                }

                const formData = new FormData(this);
                $('#start-pipeline').prop('disabled', true).text('处理中...');
                showLoading('正在上传文件…');
                updateFlowchart('upload', '正在上传文件…');

                $.ajax({
                    url: '{% url "run_pipeline" %}',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: (response) => {
                        $('#start-pipeline').prop('disabled', false).text('开始分析');
                        hideLoading();
                        if (response.status === 'success') {
                            // 逐步动画
                            let delay = 0;
                            response.progress_steps.forEach(({ step, message, duration }) => {
                                setTimeout(() => {
                                    const loadingText = {
                                        'upload': '正在上传文件…',
                                        'preprocess': '正在预处理数据…',
                                        'analysis': '正在分析数据…',
                                        'results': '正在生成结果…'
                                    }[step];
                                    showLoading(loadingText);
                                    updateFlowchart(step, message);
                                }, delay);
                                delay += duration;
                            });

                            // 显示最终结果
                            setTimeout(() => {
                                hideLoading();
                                $('#filename').val(response.filename);
                                showStatus(response.message, true);
                                updateFlowchart('results', '分析完成');
                                $('#results').html(`
                                    <h3>聚类结果</h3>
                                    <p>聚类中心:</p>
                                    ${response.cluster_centers.map((center, i) => `<p>聚类 ${i + 1}: ${center.join(', ')}</p>`).join('')}
                                    <a href="{% url 'cluster_results' %}?filename=${encodeURIComponent(response.filename)}" target="_blank" class="ant-btn ant-btn-success">查看详细报告</a>
                                `);
                            }, delay);
                        } else {
                            hideLoading();
                            showStatus(response.message, false);
                            updateFlowchart('upload', '处理出错');
                        }
                    },
                    error: (xhr) => {
                        $('#start-pipeline').prop('disabled', false).text('开始分析');
                        hideLoading();
                        showStatus(`处理失败: ${xhr.responseText}`, false);
                        updateFlowchart('upload', '处理出错');
                    },
                    xhr: function () {
                        const xhr = new XMLHttpRequest();
                        xhr.upload.addEventListener('progress', function (e) {
                            if (e.lengthComputable) {
                                const percent = (e.loaded / e.total) * 100;
                                showStatus(`上传进度: ${percent.toFixed(0)}%`, true);
                            }
                        });
                        return xhr;
                    }
                });
            });

            // Hashchange 事件
            $(window).on('hashchange', function () {
                const targetId = window.location.hash;
                if (targetId) {
                    $('.nav-item').removeClass('active');
                    $(`.nav-item[href="${targetId}"]`).addClass('active');
                    $('.content-section').removeClass('active');
                    $(targetId).addClass('active');
                }
            });

            // 初始化
            initNavigation();
        });
    </script>
</body>
</html>